package com.example.weatherpredict.utils;

import android.util.Log;

import com.blankj.utilcode.util.GsonUtils;
import com.example.weatherpredict.entity.CityBean;
import com.example.weatherpredict.entity.Weather;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class FlickFetchr {
    private static final String TAG = "FlickFetchr";

    // 书上
    public byte[] getUrlBytes(String urlSpec) throws IOException {
        URL url = new URL(urlSpec);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 跟踪重定向
        connection.setInstanceFollowRedirects(false);
        String redirect = connection.getHeaderField("Location");
        if (redirect != null) {
            connection = (HttpURLConnection) new URL(redirect).openConnection();
        }

        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream in = connection.getInputStream();

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new IOException(connection.getResponseMessage() + ": with " + urlSpec);
            }

            int byteRead = 0;
            byte[] buffer = new byte[1024];
            while ((byteRead = in.read(buffer)) > 0) {
                out.write(buffer, 0, byteRead);
            }
            out.close();
            return out.toByteArray();
        } finally {
            connection.disconnect();
        }
    }

    public String getUrlString(String urlSpec) throws IOException {
        return new String(getUrlBytes(urlSpec));
    }

    public List<Weather.DailyBean> fetchItems(String url) {
        List<Weather.DailyBean> items = new ArrayList<>();
        try {
            String jsonString = getUrlString(url);
            Log.i(TAG, "Received JSON: " + jsonString);
            Weather weather = GsonUtils.fromJson(jsonString, Weather.class);
            return weather.daily;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return items;
    }

    /**
     * 获取城市信息
     *
     * @param urlSpec
     * @return
     */
    public CityBean.LocationBean fetchCity(String urlSpec) {
        CityBean.LocationBean locationBean = null;
        try {
            String jsonString = getUrlString(urlSpec);
            Log.i(TAG, "city result: " + jsonString);
            CityBean cityBean = GsonUtils.fromJson(jsonString, CityBean.class);
            if (cityBean != null && cityBean.location != null && !cityBean.location.isEmpty()) {
                locationBean = cityBean.location.get(0);
            }
        } catch (Exception e) {
            Log.i(TAG, "Failed!" + e);
        }
        return locationBean;
    }

}
